import React from 'react';
import debounce from 'lodash/debounce';
import { Select, Spin, Tooltip } from 'antd';
import styles from '@/pages/Information/UserList/components/AddUser/style.less';
import { SelectProps } from 'antd/es/select';

interface DebounceSelectProps<ValueType = any>
  extends Omit<SelectProps<ValueType>, 'options' | 'children'> {
  fetchOptions: (search: string) => Promise<ValueType[]>;
  debounceTimeout?: number;
  tooltip:any
}


export default function DebounceSelect<ValueType extends { key?: string; label: React.ReactNode; value: string | number } = any>({fetchOptions, debounceTimeout = 800, tooltip={},...props }: DebounceSelectProps) {
  const [fetching, setFetching] = React.useState(false);
  const [options, setOptions] = React.useState<ValueType[]>([]);
  const fetchRef = React.useRef(0);

  const debounceFetcher = React.useMemo(() => {
    const loadOptions = (value: string) => {
      fetchRef.current += 1;
      const fetchId = fetchRef.current;
      setFetching(true);

      fetchOptions(value).then(newOptions => {
        console.log(tooltip,newOptions)
        if (fetchId !== fetchRef.current) {
          // for fetch callback order
          return;
        }
        setOptions(newOptions);
        setFetching(false);
      });
    };

    return debounce(loadOptions, debounceTimeout);
  }, [fetchOptions, debounceTimeout]);

  return (
    <Select<ValueType>
      filterOption={false}
      onSearch={debounceFetcher}
      notFoundContent={fetching ? <Spin size="small" /> : ' '}
      {...props}
      optionLabelProp={'value'}
    >
      {(options&&options instanceof Array)?
        ( options.map((item: any, index) =>
          <Select.Option key={index} value={item.value}>
            {item.label}
            {tooltip?(
            <Tooltip title={item[tooltip.title]}>
              <div className={styles.showDepartment}>
                {item[tooltip.show]}</div>
            </Tooltip>
            ):null}
          </Select.Option>
        )):null
      }
    </Select>
  );
}
